package com.example.shop_2212.fg

import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.OrderDetail
import com.example.base.entity.ParamPreOrder
import com.example.base.mvvm.BaseFragment
import com.example.base.net.Const
import com.example.shop_2212.R
import com.example.shop_2212.adapter.CarAdapter
import com.example.shop_2212.databinding.FragmentCarBinding
import com.example.shop_2212.fgviewmodel.CarViewModel


class CarFragment : BaseFragment<FragmentCarBinding,CarViewModel>() {
    lateinit var carAdapter: CarAdapter
    override fun getLayout(): Int = R.layout.fragment_car

    override fun getViewModel(): Class<CarViewModel> = CarViewModel::class.java

    override fun initView() {
        carAdapter = CarAdapter()
        binding.rvCar.adapter = carAdapter
        binding.rvCar.layoutManager = LinearLayoutManager(context)

        //请求数据
        viewModel.car("true","10","1")

        carAdapter.addChildClickViewIds(R.id.car_add,R.id.car_sub,R.id.car_cb)
        carAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.car_add->{
                    carAdapter.data[position].cartNum++
                    (carAdapter.getViewByPosition(position,R.id.car_num) as TextView).text = "${carAdapter.data[position].cartNum}"
                    viewModel.update(carAdapter.data[position].id,carAdapter.data[position].cartNum)
                }
                R.id.car_sub->{
                    if(carAdapter.data[position].cartNum>1){
                        carAdapter.data[position].cartNum--
                        (carAdapter.getViewByPosition(position,R.id.car_num) as TextView).text = "${carAdapter.data[position].cartNum}"
                        viewModel.update(carAdapter.data[position].id,carAdapter.data[position].cartNum)
                    }else{
                        ToastUtils.showLong("不能在减少了")
                    }
                }
                R.id.car_cb->{
                    carAdapter.data[position].isChecked = !carAdapter.data[position].isChecked//实体类中的字段别忘了添加，适配中的字段别忘了赋值
                }
            }
            check()//一定写在点击事件中
        }



        //点击管理，取消显示
        binding.tvManage.setOnClickListener {
            if(binding.llManage.isVisible){//下单显示
                //当前显示的是管理、下单按钮
                binding.tvManage.text = "取消"
                binding.llCancel.isVisible = true
                binding.llManage.isVisible = false
            }else{
                binding.tvManage.text = "管理"
                binding.llManage.isVisible = true
                binding.llCancel.isVisible = false
            }
        }
        //点击删除，删除对应选中的item
        binding.tvDelete.setOnClickListener {
            //判断是否有选中的
            val list = mutableListOf<Boolean>()
            carAdapter.data.forEach {
                list.add(it.isChecked)
            }
            if(true in list){
                var ids = arrayOf<Int>()
                carAdapter.data.forEach {
                    if(it.isChecked){
                        ids += it.id
                    }
                }
                viewModel.delete(ids)


            }else{
                ToastUtils.showLong("请至少选择一个商品")
            }

        }
        //点击立即下单，完成预下单流程
        binding.tvBuy.setOnClickListener {
            val list = mutableListOf<Boolean>()
            carAdapter.data.forEach {
                list.add(it.isChecked)
            }
            if(true in list){
                val paramPreOrder = ParamPreOrder()
                paramPreOrder.preOrderType = "shoppingCart"//下单方式
                //具体商品
                val orderDetails = mutableListOf<OrderDetail>()
                carAdapter.data.forEach {
                    if(it.isChecked){//选中的，要下单
                        val orderDetail = OrderDetail()
                        orderDetail.shoppingCartId = it.id
                        orderDetails.add(orderDetail)
                    }
                }
                paramPreOrder.orderDetails = orderDetails
                //执行下单
                viewModel.preOrder(paramPreOrder)
            }else{
                ToastUtils.showLong("请至少选择一个商品")
            }
        }

        binding.cbAll.setOnCheckedChangeListener { buttonView, isChecked ->
            binding.cbAll.setOnClickListener {
                carAdapter.data.forEach {
                    it.isChecked = isChecked
                }
                carAdapter.notifyDataSetChanged()
                check()
            }
        }

        ItemTouchHelper(object:ItemTouchHelper.Callback(){
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                val left = ItemTouchHelper.LEFT
                return makeMovementFlags(0,left)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                //左滑
                val position = viewHolder.layoutPosition
                //删除后台数据
                viewModel.delete(arrayOf(carAdapter.data[position].id))
                //删除页面
                carAdapter.data.removeAt(position)
                carAdapter.notifyItemRemoved(position)//局部刷新，不影响其他数据
                check()//重新计算金额
            }
        }).attachToRecyclerView(binding.rvCar)

    }

    private fun check() {
        //金额
        var amount = 0f
        var list = mutableListOf<Boolean>()//判断全选
        carAdapter.data.forEach {
            list.add(it.isChecked)
            if(it.isChecked){
                amount+=it.price.toFloat()*it.cartNum
            }
        }
        binding.tvMoney.text = "合计:￥$amount"
        if(false in list){
            binding.cbAll.isChecked = false
        }else{
            binding.cbAll.isChecked = true
        }
    }


    override fun initData() {
        viewModel.carSuccess.observe(this){
            if(it.code==Const.RESULT_OK){
                carAdapter.data.clear()
                carAdapter.data.addAll(it.data.list)
                carAdapter.notifyDataSetChanged()
            }
        }
        viewModel.updateSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.deleteSuccess.observe(this){
            ToastUtils.showLong(it.message)
           /* //再次请求
            viewModel.car("true","10","1")
           //直接将数据清空
            binding.tvMoney.text = "合计：￥0"
            binding.cbAll.isChecked = false*/
        }
        viewModel.preOrderSuccess.observe(this){
            if(it.code==Const.RESULT_OK){
                ToastUtils.showLong(it.toString())
                ARouter.getInstance().build("/app/PreOrderActivity").withString("preOrderNo",it.data.preOrderNo).navigation()
            }
        }
    }

}